import axios from 'axios'
import qs from 'qs'
import com from './common.js'

axios.defaults.timeout = 10000
axios.defaults.baseURL = process.env.VUE_APP_API  //VUE_APP_API_MOCK mockjs  VUE_APP_API 后端

axios.interceptors.response.use(response => {
  console.log(response)
  if (response.data.code === '0') {
    return response.data
  }else{
    switch (response.data.code) {
      case 1:
        com.toast(response.data.msg, 'error')
        break;
      case -1:
        com.toast("登录失效",'error')
      default:
        com.toast("服务器没有返回对应状态码`")
        break;
    }
    return Promise.reject(response.data)
  } 
}, error => {
    if(error.response.status!==200){
      switch (error.response.status) {
        case 408:
          com.toast('亲，网速不给力哟~');
          break;
        case 500:
          com.toast('服务器开小差了~');
          break;
        case 400:
          com.toast('参数不全')
          break;
        default:
          com.toast(`请求异常,错误码${error.response.status}`);
          break;
      }
      return Promise.reject(error)
    }
})

export function get(url,data={}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: data
    }, {
      headers: {
        "Content-Type": "application/json"
      }
    }).then((res) => {
      resolve(res)
    }).catch((e) => {
      reject(e)
    })
  })
}

export function post(url,data={}) {
  return new Promise((resolve, reject) => {
    axios.post(url, qs.stringify(data), {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      }
    }).then((res) => {
      resolve(res)
    }).catch((e) => {
      reject(e)
    })
  })
}
